package mapspinner.util;

import java.net.URISyntaxException;
import java.net.URL;
import java.util.Hashtable;
import java.util.Map;

import com.jme.image.Texture;
import com.jme.util.TextureManager;
import com.jme.util.resource.MultiFormatResourceLocator;
import com.jme.util.resource.ResourceLocatorTool;

/**
 * TextureRegistry has the purpose of caching texture filenames and indexing
 * them.
 * 
 * @author Administrator
 * 
 */
public class TextureRegistry {
	private static Map<String, MapTexture> textures = new Hashtable<String, MapTexture>();

	/**
	 * set up the textures directory
	 */
	static {
		try {
			final URL baseDir = TextureRegistry.class.getClassLoader()
					.getResource("textures/terrain/");
			final MultiFormatResourceLocator locator = new MultiFormatResourceLocator(
					baseDir, new String[] { ".tga", ".bmp", ".png", ".jpg",
							".texture", ".jme" });
			ResourceLocatorTool.addResourceLocator(
					ResourceLocatorTool.TYPE_TEXTURE, locator);
		} catch (final URISyntaxException e) {
			e.printStackTrace();
		}
	}

	/**
	 * decrements the amount of times the given texture has been used, if it
	 * reaches 0, delete it from the graphics memory
	 * 
	 * @param filename
	 *            the file name of the texture
	 */
	public static void decrementTexture(final String filename) {
		final MapTexture mt = TextureRegistry.textures.get(filename);
		mt.decrementTextureCount();
		if (mt.getTextureCount() <= 0)
			TextureManager.deleteTextureFromCard(mt.getTexture());
	}

	/**
	 * get a texture, load it if neccesary
	 * 
	 * @param filename
	 *            the filename of the texture
	 * @return the texture
	 */
	public static Texture getTexture(final String filename) {
		if (TextureRegistry.textures.keySet().contains(filename)) {
			final MapTexture mt = TextureRegistry.textures.get(filename);
			mt.incrementTextureCount();
			return mt.getTexture();
		} else {
			final Texture texture = TextureManager.loadTexture(filename,
					Texture.MinificationFilter.BilinearNearestMipMap,
					Texture.MagnificationFilter.Bilinear);
			texture.setWrap(Texture.WrapMode.Repeat);
			final MapTexture mt = new MapTexture(texture);
			mt.incrementTextureCount();
			TextureRegistry.textures.put(filename, mt);
			return mt.getTexture();
		}
	}
}